package com.yanqu.road.server.manger.activity.fivehero;

import com.yanqu.road.dao.impl.curio.UserCurioSkillDataDaoImpl;
import com.yanqu.road.entity.activity.ActivityConfig;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.fivehero.FiveHeroConfig;
import com.yanqu.road.entity.activity.fivehero.config.*;
import com.yanqu.road.entity.config.skill.SkillInfo;
import com.yanqu.road.entity.enums.eActivityType;
import com.yanqu.road.entity.enums.eSkillType;
import com.yanqu.road.entity.enums.eSystemId;
import com.yanqu.road.entity.player.UserPatrons;
import com.yanqu.road.entity.player.UserPatronsSkill;
import com.yanqu.road.entity.union.activitygroup.UnionActivityGroup;
import com.yanqu.road.logic.bussiness.activity.FiveHeroBusiness;
import com.yanqu.road.logic.helper.UnionActivityGroupHelper;
import com.yanqu.road.logic.rank.UnionRankMsgModel;
import com.yanqu.road.pb.activity.FiveHeroProto;
import com.yanqu.road.pb.union.cross.CrossUnionProto;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.fivehero.FiveHeroModule;

import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.CommonActivityRankMgr;
import com.yanqu.road.server.manger.activity.NormalActivityMgr;
import com.yanqu.road.server.manger.activity.curio.CurioMgr;
import com.yanqu.road.server.manger.config.PatronsMgr;
import com.yanqu.road.server.manger.config.SkillMgr;
import com.yanqu.road.server.manger.config.SystemOpenMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.manger.union.GameUnionActivityGroupMgr;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.RandomHelper;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class FiveHeroMgr extends TempMgr {

    private static RandomHelper randomHelper = new RandomHelper();

    private static ActivityInfo activityInfo;

    private static FiveHeroConfig config;


    public static boolean isActivityInShowTime(){
        return ActivityMgr.activityInShowTime(activityInfo);
    }

    public static boolean isActivityInTime(){
        return ActivityMgr.activityInTime(activityInfo);
    }

    public static FiveHeroConfig getConfig() {
        return config;
    }

    public static void unionChange(String unionUid) {
        try {
            //商会成员变更职位变了
            FiveHeroConfig config = FiveHeroMgr.getConfig();
            if (config != null && config.getActivityInfo() != null && ActivityMgr.activityInTime(config.getActivityInfo())) {
                FiveHeroProto.CrossFiveHeroNotifyUnionMemberChangeReqMsg.Builder builder = FiveHeroProto.CrossFiveHeroNotifyUnionMemberChangeReqMsg.newBuilder();
                builder.setActivityId(config.getActivityInfo().getActivityId());
                builder.setUnionUid(unionUid);
                /*YanQuMessage message = YanQuMessageUtils.buildMessage(CrossProtocol.C2_CROSS_FIVE_HERO_NOTIFY_UNION_MEMBER_CHANGE_REQ, builder);
                GamePlayerMgr.sendChannelPacket(0, message);*/
                int groupId = GameUnionActivityGroupMgr.getGroupId(config.getActivityInfo().getActivityId(),unionUid);
                GamePlayerMgr.sendUnionActivityGroupPacket(CrossProtocol.C2_CROSS_FIVE_HERO_NOTIFY_UNION_MEMBER_CHANGE_REQ, builder,0,config.getActivityInfo().getActivityId(),groupId);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //玩家不在线也要吧门客拉出来
    public static List<FiveHeroProto.CrossFiveHeroUpdatePatronsUserMsg> getSyncPatronsMsg(List<Long> outLineUserList) {
        List<FiveHeroProto.CrossFiveHeroUpdatePatronsUserMsg> retList = new ArrayList<>();
        Map<Long,Map<Integer, UserPatrons>> outlineUserPatronsMap = PatronsMgr.getSomeUserPatronsMap(outLineUserList);
        List<Integer> skillIdList = CurioMgr.getSkillIdList(eSkillType.FiveHeroAttackSkill.getValue());
        for(long userId : outlineUserPatronsMap.keySet()){
            long addition = new UserCurioSkillDataDaoImpl().getUserCurioSkillAddition(userId, skillIdList);
            FiveHeroProto.CrossFiveHeroUpdatePatronsUserMsg.Builder builder = FiveHeroProto.CrossFiveHeroUpdatePatronsUserMsg.newBuilder();
            builder.setUserId(userId);
            Map<Integer, UserPatrons> patronsMap = outlineUserPatronsMap.get(userId);
            for(UserPatrons userPatrons : patronsMap.values()){
                FiveHeroProto.FiveHeroPatronsTempMsg.Builder patronsMsg = FiveHeroProto.FiveHeroPatronsTempMsg.newBuilder();
                patronsMsg.setId(userPatrons.getPatronsId());
                patronsMsg.setSkin(userPatrons.getSkinId());
                patronsMsg.setAbility(userPatrons.getAbility().longValue());
                patronsMsg.setAddPer(getSkillAddPer(userPatrons));
                builder.addPatrons(patronsMsg);
            }
            builder.setCurioAddition(addition);
            retList.add(builder.build());
        }
        return retList;
    }

    public static int getSkillAddPer(UserPatrons userPatrons){
        int addValue = 0;
        for(UserPatronsSkill skill : userPatrons.getSkillList()){
            SkillInfo skillInfo = SkillMgr.getSkillInfo(skill.getSkillId());
            if(skillInfo.getType() == eSkillType.FiveHeroSkillAddition.getValue()){
                addValue = addValue + SkillMgr.getSkillAddition(skillInfo,skill.getSkillLv());
            }
        }
        return addValue;
    }

    public static boolean isPopularityItemId(int goodsId) {
        if(config == null){
            return false;
        }
        return config.getPopularityItemId() == goodsId;
    }

    public static String getWorshipReward(int campId){
        Property rewardProperty = new Property();
        if(campId == 0){
            Map<Integer, List<Integer>> worshipRewardMap = config.getBigWorshipRewardMap();
            for(int goodsId : worshipRewardMap.keySet()){
                List<Integer> randomValueList = worshipRewardMap.get(goodsId);
                rewardProperty.addProperty(goodsId, BigInteger.valueOf(randomHelper.next(randomValueList.get(0),randomValueList.get(1) + 1)));
            }
        }else if(campId > 0 && campId <= config.getCampCount()){
            Map<Integer, List<Integer>> worshipRewardMap = config.getSmallWorshipRewardMap();
            for(int goodsId : worshipRewardMap.keySet()){
                List<Integer> randomValueList = worshipRewardMap.get(goodsId);
                rewardProperty.addProperty(goodsId, BigInteger.valueOf(randomHelper.next(randomValueList.get(0),randomValueList.get(1) + 1)));
            }
        }else{
            //乱发的
        }
        return PropertyHelper.parsePropertyToString(rewardProperty);
    }

    public static boolean canChangeUnion() {
        long now = System.currentTimeMillis();
        if (config != null && config.getActivityInfo() != null
                && now > config.getRegisterTimeList().get(1) // [报名期结束,活动结束] 无法退出
                && now < config.getActivityInfo().getEndTime() * 1000L) {
            return false;
        }
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        return true;
    }

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean stop() {
        return false;
    }

    public static void reloadActivityData() {
        getLogger().info("reload fivehero activity start");

        // 获取活动
        ActivityInfo tmpActivityInfo;
        FiveHeroConfig tempActivityConfig;
        List<ActivityInfo> openActivityInfoList = NormalActivityMgr.getOpenActivityInfoList(eActivityType.FiveHero.getValue());
        if (openActivityInfoList.size() <= 0) {
            getLogger().info("no fivehero activity in show time");
            //用是不是有活动判断是不是
            if(config != null){
                config.setActivityInfo(null);
            }
            return;
        }
        tmpActivityInfo = openActivityInfoList.get(0);
        Map<Integer, FiveHeroTypeConfig> tmpTypeConfigMap = FiveHeroBusiness.getTypeConfigMap(tmpActivityInfo.getActivityId());
        Map<Integer, FiveHeroCityConfig> tmpCityConfigMap = FiveHeroBusiness.getCityConfigMap(tmpActivityInfo.getActivityId());
        Map<Integer, FiveHeroBuffConfig> tmpBuffConfigMap = FiveHeroBusiness.getBuffConfigMap(tmpActivityInfo.getActivityId());
        Map<Integer, FiveHeroEventConfig> tmpEventConfigMap = FiveHeroBusiness.getEventConfigMap(tmpActivityInfo.getActivityId());
        Map<Integer, FiveHeroBookConfig> tmpBookConfigMap = FiveHeroBusiness.getBookConfigMap(tmpActivityInfo.getActivityId());
        Map<Integer, FiveHeroBanditConfig> tmpBanditConfigMap = FiveHeroBusiness.getBanditConfigMap(tmpActivityInfo.getActivityId());
        Map<Integer, FiveHeroTechConfig> tmpTechConfigMap = FiveHeroBusiness.getTechConfigMap(tmpActivityInfo.getActivityId());
        Map<Integer, FiveHeroOrderConfig> tmpOrderConfigMap = FiveHeroBusiness.getOrderConfigMap(tmpActivityInfo.getActivityId());
        Map<Integer, FiveHeroTitleConfig> tmpTitleConfigMap = FiveHeroBusiness.getTitleConfigMap(tmpActivityInfo.getActivityId());

        Map<String, ActivityConfig> activityConfigMap = NormalActivityMgr.getActivityConfigMap(tmpActivityInfo.getActivityId());
        tempActivityConfig = new FiveHeroConfig();
        tempActivityConfig.setActivityInfo(tmpActivityInfo);
        tempActivityConfig.initConfig(activityConfigMap,tmpTypeConfigMap,tmpCityConfigMap,tmpBuffConfigMap,tmpEventConfigMap,tmpBookConfigMap,tmpBanditConfigMap,tmpTechConfigMap,tmpOrderConfigMap,tmpTitleConfigMap);

        // 活动配置
        activityInfo = tmpActivityInfo;
        config = tempActivityConfig;

        reloadPlayerData();
        getLogger().info("reload fivehero activity end");
    }


    private static void reloadPlayerData() {
        if (ActivityMgr.activityInShowTime(activityInfo)) {
            for (GamePlayer player : GamePlayerMgr.getCopyPlayerMap().values()) {
                if (SystemOpenMgr.systemOpen(player, eSystemId.FiveHeroActivity.getValue())) {
                    FiveHeroModule module = player.getModule(FiveHeroModule.class);
                    module.initUserData(activityInfo.getActivityId());
                    module.syncUserData(true);
                }
            }
        }
    }

    public static ActivityInfo getActivityInfo() {
        return activityInfo;
    }

    public static boolean hasActivity() {
        if (activityInfo == null || config == null) {
            return false;
        }
        return true;
    }

    public static boolean isInRegistration() {
        if(config != null && activityInfo != null){
            long nowTime = System.currentTimeMillis();
            if(nowTime > activityInfo.getBeginShowTime() * 1000 && nowTime < config.getRegisterTimeList().get(1)){
                return true;
            }
        }
        return false;
    }
    /**
     * 检查有没有缓存到报名期排行
     */
    public static void checkRegistrationList() {
        if (config == null || config.getActivityInfo() == null) {
            return;
        }
        ActivityInfo activityInfo = config.getActivityInfo();
        // 判断无需分组活动
        if (!UnionActivityGroupHelper.needGroup(activityInfo)) {
            UnionRankMsgModel model = CommonActivityRankMgr.getUnionRankMsgModel(activityInfo.getActivityId());
            if (null != model) {
                model.setRankNum(config.getSignUpUnionCount() + 50);
                model.setActivityEndTime(activityInfo.getEndShowTime());
                if (model.getRankListMsg().getRankListCount() == 0 && !model.isInReq()) {
                    CrossUnionProto.CrossUnionGetMaxAbilityUnionRankListReq.Builder crossReqMsg = CrossUnionProto.CrossUnionGetMaxAbilityUnionRankListReq.newBuilder();
                    crossReqMsg.setActivityId(activityInfo.getActivityId());
                    crossReqMsg.addAllServerIds(activityInfo.getServerIdList());
                    crossReqMsg.setRankNum(model.getRankNum());
                    crossReqMsg.setActivityEndTime(activityInfo.getEndShowTime());
                    GamePlayerMgr.sendPacket(0, YanQuMessageUtils.buildMessage(Protocol.C_UNION_GET_MAX_ABILITY_UNION_RANK_LIST, crossReqMsg));
                }
            }
        } else {
            Map<Integer, UnionActivityGroup> groupMap = GameUnionActivityGroupMgr.getGroupMap(activityInfo.getActivityId());
            if (groupMap == null) {
                return;
            }
            for (Integer groupId : groupMap.keySet()) {
                UnionRankMsgModel model = CommonActivityRankMgr.getUnionRankMsgModelByGroup(activityInfo.getActivityId(), groupId);
                if (null != model) {
                    model.setRankNum(config.getSignUpUnionCount() + 50);
                    model.setActivityEndTime(activityInfo.getEndShowTime());
                    if (model.getRankListMsg().getRankListCount() == 0 && !model.isInReq()) {
                        CrossUnionProto.CrossUnionGetMaxAbilityUnionRankListReq.Builder crossReqMsg = CrossUnionProto.CrossUnionGetMaxAbilityUnionRankListReq.newBuilder();
                        crossReqMsg.setActivityId(activityInfo.getActivityId());
                        crossReqMsg.addAllServerIds(activityInfo.getServerIdList());
                        crossReqMsg.setRankNum(model.getRankNum());
                        crossReqMsg.setActivityEndTime(activityInfo.getEndShowTime());
                        crossReqMsg.setGroupId(groupId);
                        GamePlayerMgr.sendPacket(0, YanQuMessageUtils.buildMessage(Protocol.C_UNION_GET_MAX_ABILITY_UNION_RANK_LIST, crossReqMsg));
                    }
                }
            }
        }


    }

}
